package com.bestcem.xm.user.util.business;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

/**
 * 校验工具类
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/2/23 10:00
 */
public class ValidatorUtil {

    private ValidatorUtil() {
    }

    /**
     * 快速失败模式-Validator
     */
    private static final Validator FAIL_FAST_VALIDATOR = Validation.byProvider(HibernateValidator.class)
            .configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 校验-快速失败模式
     *
     * @param param 校验参数
     * @return ServiceResult<Object>
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @date 2022/3/31 13:14
     */
    public static ServiceResult<Object> validateFast(Object param) {
        if (Objects.isNull(param)) {
            return ServiceResult.success();
        }

        // 快速失败模式
        Set<ConstraintViolation<Object>> levelViolationSet = FAIL_FAST_VALIDATOR.validate(param);
        Iterator<ConstraintViolation<Object>> iterator = levelViolationSet.iterator();
        if (iterator.hasNext()) {
            ConstraintViolation<Object> next = iterator.next();
            String[] messages = next.getMessage().split(";");
            String errorCode = messages[0];
            String message = messages[1];
            String errorMsg = MessageFormat.format(message, next.getInvalidValue());
            return ServiceResult.fail(errorMsg).setErrorCode(errorCode);
        }

        return ServiceResult.success();
    }

}
